package cn.bdqn.service;

import cn.bdqn.pojo.SysJobPo;
import cn.bdqn.task.CronTaskRegistrar;
import cn.bdqn.thread.SchedulingRunnable;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 当springboot项目启动完成后，加载数据库里状态为正常的定时任务
 */
@Service
public class SysJobRunner implements CommandLineRunner {

 @Autowired
 private SysJobPoService sysJobPoService;

 @Autowired
 private CronTaskRegistrar cronTaskRegistrar;

 @Override
 public void run(String... args) {
  List<SysJobPo> jobList = sysJobPoService.getByStatus(1);
  if (CollectionUtils.isNotEmpty(jobList)) {
   for (SysJobPo job : jobList) {
    SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParams());
    cronTaskRegistrar.addCronTask(task, job.getCronExpression());
   }
   System.out.println("定时任务已加载完毕...");
  }
 }
}